package main

import (
	"context"
	"flag"
	"fmt"
	"github.com/zeromicro/go-zero/core/logc"
	"github.com/zeromicro/go-zero/core/service"
	"go-zero-demo/app/datacenter/mq/internal/mqs"
	"os"
	"os/signal"
	"sync/atomic"
	"syscall"
	"time"

	"go-zero-demo/app/datacenter/mq/internal/config"
	"go-zero-demo/app/datacenter/mq/internal/svc"

	"github.com/zeromicro/go-zero/core/conf"
)

var configFile = flag.String("f", "app/datacenter/mq/etc/mq.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	logc.MustSetup(c.Log)

	// 消息队列
	svcCtx := svc.NewServiceContext(c)
	ctx := context.Background()

	server := mqs.NewServer(ctx, svcCtx)
	server.Run()
	serviceGroup := service.NewServiceGroup()
	defer serviceGroup.Stop()
	//for _, mq := range mqs.Consumers(c,ctx, svcCtx) {
	//   serviceGroup.Add(mq)
	//}
	var state int32 = 1
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)

EXIT:
	for {
		sig := <-quit
		fmt.Sprintln("HTTP server received signal: %v", sig.String())
		switch sig {
		case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
			atomic.CompareAndSwapInt32(&state, 1, 0)
			break EXIT
		case syscall.SIGHUP:
		default:
			break EXIT
		}
	}

	fmt.Println("server exit!")
	time.Sleep(3 * time.Second)
	os.Exit(int(atomic.LoadInt32(&state)))

}
